package com.bdqn.tour.servlet.Hzy;

import com.alibaba.fastjson.JSON;
import com.bdqn.tour.util.HzySMS.SMSUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * packageName com.csdj.web
 *
 * @author winver
 * @version 1.0
 * @className SendSMSServlet
 * @date 2024/12/17
 * @description TODO
 */
@WebServlet("/SendSms")
public class SendSMSServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain;charset=utf-8");
        //获取手机号码
        String phone = req.getParameter("phone");

        // 如果请求参数中没有，再从session获取
        if (phone == null || phone.isEmpty()) {
            phone = (String) req.getSession().getAttribute("phone");
        }

        //随机生成一个数字验证码
        String valCode = getValCode();
        System.out.println("验证码:" + valCode);
        PrintWriter out = resp.getWriter();
        Map<String, Object> map = new HashMap<>();
        //发送短信
        if (SMSUtil.sendSms(phone, valCode)) {
            //if (true) {
            map.put("code", "0000");
            //在会话中共享验证码，方便等会验证
            req.getSession().setAttribute(phone, valCode);
        } else {
            map.put("code", "1001");
        }
        //转成字符串
        String json = JSON.toJSONString(map);
        out.print(json);
        out.close();

    }

    public String getValCode() {
        StringBuffer valCode = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            valCode.append((int) (Math.random() * 10));
        }
        return valCode.toString();
    }
}
